import {Row, Col, Tree, Modal, Table, Tooltip, Tabs, Select, Menu, Button, Spin, Input, Form} from 'antd';
// import Tree from '../../../_antd1.11.2/Tree';
// import Row from '../../../_antd1.11.2/Row';
// import Col from '../../../_antd1.11.2/Col';
// import Modal from '../../../_antd1.11.2/Modal';
// import Tooltip from '../../../_antd1.11.2/Tooltip';
// import Tabs from '../../../_antd1.11.2/Tabs';
// import Table from '../../../_antd1.11.2/Table';
const TabPane = Tabs.TabPane;
const TreeNode = Tree.TreeNode;
// import Select from '../../../_antd1.11.2/Select';
const Option = Select.Option;
// import Menu from '../../../_antd1.11.2/menu';
// import Button from '../../../_antd1.11.2/Button';
// import Spin from '../../../_antd1.11.2/Spin';
// import Input from '../../../_antd1.11.2/Input';
// import Form from '../../../_antd1.11.2/Form'
const FormItem = Form.Item;
import isEmpty from 'lodash/isEmpty';
import keys from 'lodash/keys';
import values from 'lodash/values';
import cloneDeep from 'lodash/cloneDeep';
import isEqual from 'lodash/isEqual';
import isArray from 'lodash/isArray';
import WeaTools from '../../wea-tools';
import WeaSearchBrowserBox from '../wea-search-browser-box';
import forEach from 'lodash/forEach';
import WeaScroll from '../../wea-scroll';
import WeaInputSearch from '../../wea-input-search';
import WeaBrowserSingleList from '../wea-browser-single-list';
import WeaBrowserSingleTree from '../wea-browser-single-tree';
import WeaAssociativeSearch from '../wea-associative-search';
import WeaInput from '../../wea-input';
import WeaSelect from '../../wea-select';
import WeaBrowser from '../../wea-browser';
import WeaDateGroup from '../../wea-date-group';
import WeaBrowserSearch from '../../wea-browser-search';
import debounce from 'lodash/debounce'

class Main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible:false,
            loading: true,
            showDrop: false,
            id:"",
            name:'',
            isClearData: false,
            idCache: '',
            nameChache: '',
            dataKey:'',//sessionkey
            contentType:'',
            noPgTableData:{},
            browserConditions:[],
            showSearchAd:false,
            selectedValue:'',
            inputValue:'',
            activeKey: props.tabs && this.getDefaultKey(props.tabs)|| '1',
            count:0,
            quickSearch: props.quickSearchName || '',
            treeDatas: [],
            defaultExpandedKeys: [],
            pageSize: props.pageSize || 20,
            loadAllTreeData: false,
        }
    }
    componentDidMount(){
        const {value, valueSpan} = this.props;
        if(!isEmpty(value) && valueSpan){
            this.setState({id: value, name: valueSpan});
        }
        // 默认显示数据
        if (!isEmpty(this.props.replaceDatas)) {
            let name = this.props.replaceDatas[0].name;
            let id = this.props.replaceDatas[0].id;
            this.setState({id: id, name: name});
            // this.throwCurrentState(id, name);
        }
    }
    componentWillReceiveProps(nextProps,nextState) {
        if (this.props.value !== nextProps.value && isEmpty(nextProps.value)) {
            this.setState({id: '', name: '', isClearData: !this.state.isClearData});
        }
        if(this.props.value !== nextProps.value && !isEmpty(nextProps.value) && nextProps.valueSpan){//form value改变&&有值
            this.setState({id:nextProps.value, name:nextProps.valueSpan});
            // this.throwCurrentState(nextProps.value, nextProps.valueSpan);
        }
        if (!isEqual(this.props.replaceDatas, nextProps.replaceDatas)) {
            let id = '', name = '';
            if (!isEmpty(nextProps.replaceDatas)) {
                name = nextProps.replaceDatas[0].name;
                id = nextProps.replaceDatas[0].id;
            } else {
                this.setState({isClearData: !this.state.isClearData})
            }
            this.setState({id: id, name: name});
            // this.throwCurrentState(id, name);
        }
    }
    set(datas) {
        let id = '', name = '';
        if (!isEmpty(datas)) {
            name = datas[0].name;
            id = datas[0].id;
        } else {
            this.setState({isClearData: !this.state.isClearData})
        }
        this.setState({id: id, name: name});
    }
    shouldComponentUpdate(nextProps,nextState) {
        return this.state.visible !== nextState.visible
        || this.state.loading !== nextState.loading
        || this.state.showDrop !== nextState.showDrop
        || this.state.id !== nextState.id
        || this.state.name !== nextState.name
        || this.state.isClearData !== nextState.isClearData
        || this.state.idCache !== nextState.idCache
        || this.state.nameChache !== nextState.nameChache
        || (this.state.dataKey!==nextState.dataKey&&!isEmpty(this.state.dataKey)&&!isEmpty(nextState.dataKey))
        || this.state.contentType !== nextState.contentType
        || this.state.noPgTableData !== nextState.noPgTableData
        || this.state.browserConditions !== nextState.browserConditions
        || this.state.showSearchAd !== nextState.showSearchAd
        || this.state.selectedValue !== nextState.selectedValue
        || this.state.inputValue !== nextState.inputValue
        || this.state.url !== nextState.url
        || this.state.activeKey !== nextState.activeKey
        || this.state.count !== nextState.count
        || this.state.loadAllTreeData !== nextState.loadAllTreeData
        || !isEqual(this.state.treeDatas, nextState.treeDatas)
        || !isEqual(this.props.replaceDatas, nextProps.replaceDatas)
        || !isEqual(this.state.hasPgTableData, nextState.hasPgTableData)
        || this.props.type !== nextProps.type
        || this.props.viewAttr !== nextProps.viewAttr
        || this.props.fieldName !== nextProps.fieldName
        || this.props.title !== nextProps.title
        || this.props.tabs !== nextProps.tabs
        || this.props.form !== nextProps.form
    }
    setLoading(bool) {
        this.setState({loading: bool});
    }
    initialState=(params = {})=> {
        this.props.form && this.props.form.resetFields();
        this.fetchData(this.getUrl(), params);
        this.setState({inputValue:''});
    }
    fetchData(url='',param={}){
        const {dataUrl,type, topPrefix} = this.props;
        const {pageSize} = this.state;
        url = url ? url : dataUrl;
        param['min'] = 1;
        param['max'] = 1 * pageSize;
        param['pageSize'] = pageSize;
        url =  `${url}${WeaTools.getFd(param)}`;
        this.setState({url});
        this.setLoading(true);
        WeaTools.callApi(url).then((data)=> {
            if(data.type == 1){//datakeyHasPgTable
                this.setState({
                    dataKey:data.datas,
                    contentType:'dk_hasPgTable',
                });
            }
            if(data.type == 2){//nodatakeyNoPgTable
                this.setState({
                    noPgTableData:{columns:data.columns,datas:data.datas},
                    contentType:'noPgTable',
                });
                this.setLoading(false);
            }
            if(data.type == 3){//Tree
                let defaultExpandedKeys = [];
                if (data.datas && data.datas.id) {
                    defaultExpandedKeys.push(`${topPrefix}0-${data.datas.id}`)
                }
                if (!isEmpty(data.datas)) {
                    this.setState({
                        contentType:'Tree',
                        treeDatas: data.datas,
                        defaultExpandedKeys: defaultExpandedKeys,
                        loadAllTreeData: data.isLoadAll,
                    })
                } else {
                    this.setState({
                        contentType: ''
                    })
                }
                this.setLoading(false);
            }
            if(data.type == 4){//nodatakeyHasPgTable
                this.setState({
                    hasPgTableData: {columns:data.columns, datas:data.datas, count:data.total},
                    contentType:'hasPgTable',
                });
                this.setLoading(false);
            }
        });
    }
    showModal=(bool)=> this.setState({visible: bool});
    handleOk=()=> {
        const {idCache,nameChache} = this.state;
        this.throwCurrentState(idCache,nameChache);
        this.setState({
            id: idCache,
            name: nameChache,
            browserConditions: [],
            visible: false,
            showSearchAd: false,
            activeKey: this.getDefaultKey(this.props.tabs),
            url: '',
            selectedValue: '',
            contentType: '',
        });
        const {resetFields} = this.props.form;
        resetFields(); // 重置高级搜索
        this.showModal(false);
    }
    handleCancel=()=>{
        const {resetFields} = this.props.form;
        resetFields(); // 重置高级搜索
        this.setState({
            activeKey: this.getDefaultKey(this.props.tabs),
            browserConditions: [],
            showSearchAd: false,
            idCache: '',
            nameChache: '',
            url: '',
            selectedValue: '',
            contentType: '',
        });
        this.showModal(false);
    }
    handleClear=()=> {
        const {resetFields} = this.props.form;
        resetFields(); // 重置高级搜索
        this.throwCurrentState('','');
        this.setState({
            activeKey: this.getDefaultKey(this.props.tabs),
            browserConditions: [],
            selectedValue: '',
            idCache: '',
            nameChache: '',
            showSearchAd: false,
            isClearData: !this.state.isClearData,
            url: '',
            contentType: '',
        });
        this.showModal(false);
    }
    onCustomClick = (e) => {
        e.preventDefault();
        this.onBrowerClick();
    }
    onBrowerClick = (v)=>{
        const {conditionURL, hasAdvanceSerach} = this.props;
        this.setState({inputValue: ''});
        if (hasAdvanceSerach) {
            // 获取高级搜索 condition
            WeaTools.callApi(conditionURL).then(data=>{
                let quickSearch = '';
                if (!isEmpty(data.conditions)) {
                    data.conditions.forEach((item)=> {
                        if (item.isQuickSearch) {
                            quickSearch = item.domkey[0];
                        }
                    })
                }
                const params = WeaTools.getParamsByConditions(data.conditions);
                this.initialState(params);//初始化浏览框
                this.browserConditionsBk = data.conditions;
                this.defaultConditionParams = {...params};
                if (!isEmpty(params)) {
                    // 初始条件更新在form中
                    const {setFieldsValue} = this.props.form;
                    setFieldsValue(params);
                    conditionParamsBK = {...params};
                }
                this.setState({
                    browserConditions:data.conditions,
                    inputValue: params[quickSearch] || '',
                    selectedValue: params['date2during'] || '',
                    quickSearch
                });
            });
        } else {
            this.initialState();//初始化浏览框
        }
        if (!isEmpty(v)) {
            this.setState({idCache: v[0].id, nameChache: v[0].name});
        } else {
            this.setState({id: '', name: '', idCache: '', nameChache: ''})
        }

        this.showModal(true);
    }
    onBrowerChangeHandler = (id,name)=>{
        this.throwCurrentState(id,name);
    }
    renderList(hasPagination,contentType){
        const {browserConditions,dataKey,noPgTableData,hasPgTableData,pageSize}=this.state;
        const tableConfig = ()=>{
            if(hasPagination && contentType=='dk_hasPgTable'){
                return {dataKey:dataKey}
            }
            if(hasPagination && contentType=='hasPgTable'){
                return {hasPgTableData:hasPgTableData}
            }
            if(!hasPagination && contentType=='noPgTable'){
                return {noPgTableData:noPgTableData}
            }
        }
        return (
            <WeaBrowserSingleList
                {...tableConfig()}
                pageSize={pageSize}
                url={this.state.url}
                contentType={contentType}
                hasPagination={hasPagination}
                setData={this.setListData.bind(this)}
                setLoading={this.setLoading.bind(this)}
                {...this.props}
            />
        );
    }
    onSearchChange=(v)=>{
        this.setState({inputValue: v});
        const {quickSearch, selectedValue} = this.state;
        const {setFieldsValue} = this.props.form;
        let params = this.getFields();
        params[quickSearch] = v;
        if (selectedValue) params['date2during'] = selectedValue;
        setFieldsValue(params); // 高级搜索数据联动
        let url = this.getUrl(true);
        this.fetchData(url, params);
    }
    search=(e) => {
        const {quickSearch} = this.state;
        e.preventDefault();
        let params = this.getFields();
        let url = this.getUrl(true);
        this.fetchData(url, params);
        this.setState({
            showSearchAd:false,
            inputValue: params[quickSearch] || ''
        });
        if (params['date2during']) {
            this.setState({selectedValue: params['date2during']});
        }
    }
    getFields() {
        const {validateFields} = this.props.form;
        let params = {};
        validateFields((errors, object) => {
            if (!!errors) {
                return;
            }
            let newObject = cloneDeep({...object,...conditionParamsBK});
            forEach(newObject, (value, key) => {
                if (value) params[key] = value;
            })
        });
        return params;
    }
    renderTree(hasPagination){
        const {type} = this.props;
        const {idCache, nameChache, url, treeDatas, defaultExpandedKeys, loadAllTreeData} = this.state;
        const showDropMenu = type=='4'|| type =='164'
        return(
            <WeaBrowserSingleTree
                url={url}
                id={idCache}
                name={nameChache}
                treeDatas={treeDatas}
                defaultExpandedKeys={defaultExpandedKeys}
                showDropMenu={showDropMenu}
                setData={this.setTreeData.bind(this)}
                {...this.props}
                isLoadAll={loadAllTreeData}
            />
        );
    }
    getDefaultKey(tabs) {
        if (!isEmpty(tabs)) {
            tabs.forEach((tab)=> {
                if (tab.selected) {
                    return tab.key;
                }
            })
            return tabs[0].key;
        }
    }
    getUrl(searched = false, activeKey) {
        activeKey = activeKey || this.state.activeKey;
        const {tabs, dataUrl} = this.props;
        let url = dataUrl;
        let tab = {};
        if (!isEmpty(tabs)) {
            tab = tabs.filter(m=>m.key==activeKey)[0];
        }
        if (searched && !isEmpty(tabs)) {
            tabs.forEach((t)=> {
                if (t.isSearch) {
                    tab = t;
                    this.setState({activeKey: t.key});
                }
            })
        }
        if (tab.url) {
            url = tab.url;
        }
        if (!isEmpty(tab.dataParams)) {
            url = `${url}${WeaTools.getFd(tab.dataParams)}&`;
        }
        return url;
    }
    onTabsChange=(activeKey)=> {
        const {resetFields, setFieldsValue} = this.props.form;
        this.setState({browserConditions: []});
        resetFields();
        const url = this.getUrl(false, activeKey);
        this.fetchData(url, this.defaultConditionParams);
        const quickSearch = this.state.quickSearch;
        this.setState({
            url,
            activeKey,
            showSearchAd: false,
            browserConditions: this.browserConditionsBk,
        });
        if (!isEmpty(this.defaultConditionParams)) {
            conditionParamsBK = {...this.defaultConditionParams};
            this.setState({
                inputValue: this.defaultConditionParams[quickSearch] || '',
                selectedValue: this.defaultConditionParams['date2during'] || '',
            });
        }
    }
    renderTab() {
        const {tabs} = this.props;
        let TabPanes = [];
        if (!isEmpty(tabs)) {
            tabs.forEach((tab) => {
                TabPanes.push(<TabPane tab={tab.name} key={tab.key}></TabPane>)
            });
            return (
                <Tabs onChange={this.onTabsChange} activeKey={this.state.activeKey}>
                    {TabPanes}
                </Tabs>
            );
        }
        return;
    }
    getSearchType() {
        let r = [];
        const {quickSearch} = this.state;
        const {hasAdvanceSerach} = this.props;
        if (quickSearch) {
            r.push('base');
        }
        if (hasAdvanceSerach) {
            r.push('advanced');
        }
        return r;
    }
    topComponents =()=> {
        const {inputValue,showSearchAd,selectedValue,browserConditions,activeKey} = this.state;
        const {type, hasAdvanceSerach} = this.props;
        const {quickSearch} = this.state;
        const tab = this.renderTab();
        const showTop = tab || hasAdvanceSerach || quickSearch;
        const addSelect = ()=>{
            let options = [];
            if(type == '16'){
                browserConditions.forEach((m)=>{
                    if (m.domkey[0]=='date2during') {
                        options = m.options;
                    }
                })
            }
            if (options.length > 0) {
                return (
                    <WeaSelect
                        style={{width: '100px'}}
                        value={selectedValue}
                        options={options}
                        onChange={this.doChangeEvent}
                    />
                );
            }
        }
        if (showTop) {
            return (
                <WeaBrowserSearch
                    buttonsAd={this.getTabButtonsAd()}
                    addSelect={type=='16' ? addSelect():''}
                    tabs={tab}
                    searchType={this.getSearchType()}
                    searchsBaseValue={inputValue}
                    searchsAd={<Form horizontal>{this.getSearchs()}</Form>}
                    showSearchAd={showSearchAd}
                    setShowSearchAd={(bool)=>{this.setShowSearchAd(bool)}}
                    onSearchChange={(v)=>{this.setState({inputValue: v})}}
                    onSearch={this.onSearchChange.bind(this)}
                />
            )
        }
    }
    setShowSearchAd(bool){
        const {showSearchAd}=this.state;
        this.setState({showSearchAd:bool})
    }
    render() {
        const {icon,iconBgcolor,title,topPrefix,value,type,modalStyle,customized}  = this.props;
        const {showDrop,listDatas,listColumns,id,name,visible,contentType,loading} = this.state;
        const titleEle = (
            <Row>
                <Col span="22" style={{paddingLeft:20,lineHeight:'48px'}}>
                    <div className="wea-browser-single-title">
                        {iconBgcolor ?
                        <div className="wea-browser-single-icon-circle" style={{background: iconBgcolor}}>
                            <i className={icon}/>
                        </div>
                        : <span style={{verticalAlign:'middle',marginRight:10}}><i className={icon}/></span>
                        }
                        <span style={{verticalAlign:'middle'}}>{title}</span>
                    </div>
                </Col>
            </Row>
        );
        let inputArr = (
            <div className="ant-search-custom">
                <Input key="theInput"  addonAfter={<div style={{ "cursor": "pointer" }}>
                    <i onClick={this.showModal.bind(this) } className="anticon anticon-search" ></i>
                </div>} value={typeof value === 'undefined' ? '' : name} />
            </div>
        );
        if(!!type){
            inputArr =(
                <WeaAssociativeSearch
                    {...this.props}
                    style={this.props.inputStyle}
                    isClearData={this.state.isClearData}
                    type={type}
                    value={value}
                    ids={id}
                    names={name}
                    clickCallback={this.onBrowerClick}
                    onChange={this.onBrowerChangeHandler}
                />
            );
        }
        let dom = inputArr;
        if (customized) {
            dom = (
                <div className="cursor-pointer" onClick={this.onCustomClick}>
                    {this.props.children}
                </div>
            )
        }
        const hasPagination = contentType=='hasPgTable'||contentType=='dk_hasPgTable';
        const isList = contentType=='noPgTable'||contentType=='hasPgTable'||contentType=='dk_hasPgTable';
        const isTree = contentType=='Tree';
        return (
            <div>
               {dom}
               <input type="hidden" id={this.props.fieldName} name={this.props.fieldName} value={id} />
               <Modal
                  wrapClassName="wea-browser-single wea-browser-modal"
                  title={titleEle}
                  zIndex={this.props.zIndex}
                  width={modalStyle.width}
                  // style={modalStyle}
                  maskClosable={false}
                  visible={visible}
                  onCancel={this.handleCancel.bind(this)}
                  footer= {[
                        isTree && <Button key="submit" type="primary" size="large" onClick={this.handleOk.bind(this)}>确 定</Button>,
                        <Button key="clear" type="ghost" size="large" onClick={this.handleClear.bind(this)}>清 除</Button>,
                        <Button key="back" type="ghost" size="large" onClick={this.handleCancel.bind(this)}>取 消</Button>,
                        ]}
                >
                {this.topComponents()}
                <Spin spinning={loading}>
                    <div style={{minHeight: 440}}>
                        {isList && this.renderList(hasPagination,contentType)}
                        {isTree && this.renderTree(hasPagination,contentType)}
                    </div>
                </Spin>
               </Modal>
            </div>
        );

    }
    resetFields() {
        const {resetFields,setFieldsValue} = this.props.form;
        const {browserConditions} = this.state;
        const fields = {};
        browserConditions.forEach((c) => {
            let ct = c.conditionType.toUpperCase();
            let domkey = c.domkey[0];
            const filterKeys = [1, -1, '1', '-1'];
            if (ct === 'BROWSER') {
                if (!isEmpty(c.browserConditionParam) && filterKeys.indexOf(c.browserConditionParam.viewAttr) == -1) {
                    fields[domkey] = undefined;
                    conditionParamsBK[domkey] = '';
                }
            } else {
                if (filterKeys.indexOf(c.viewAttr) == -1) {
                    fields[domkey] = undefined;
                    conditionParamsBK[domkey] = '';
                }
            }
        })
        setFieldsValue(fields);
    }
    doChangeEvent=(v)=>{
        const {setFieldsValue} = this.props.form;
        const url = this.getUrl();
        let params = this.getFields();
        params.date2during = v;
        this.fetchData(url, params);
        this.setState({selectedValue:v});
        setFieldsValue({date2during: v});
    }
    getTabButtonsAd() {
        return [
            <Button type="primary" onClick={(e)=>this.search(e)}>搜索</Button>,
            <Button type="ghost" onClick={(e)=>{this.reset()}}>重置</Button>,
            <Button type="ghost" onClick={()=>{this.setState({showSearchAd:false})}}>取消</Button>
        ]
    }
    reset() {
        this.resetFields();
        this.setState({inputValue: ''});
    }
    getSearchs(){
        const {browserConditions} = this.state;
        let items = new Array();
        !!browserConditions && browserConditions.forEach( field => {
            items.push({
                com:(<FormItem
                    label={`${field.label}`}
                    labelCol={{span: `${field.labelcol}`}}
                    wrapperCol={{span: `${field.fieldcol}`}}>
                        {WeaTools.getComponent(field.conditionType, field.browserConditionParam, field.domkey,this.props, field)}
                    </FormItem>),
                colSpan:field.colSpan || 2,
                hide: WeaTools.isComponentHide(field),
            });
        });
       return <WeaSearchBrowserBox items={items} />
    }

    throwCurrentState(id = '', name){
        const data = [];
        if (id || name) {
            data.push({
                id: id.toString(),
                name: name,
            })
        }
        this.props.onChange && this.props.onChange(id.toString(), name, data);
    }
    setListData(id,name){
        this.throwCurrentState(id,name);
        this.setState({
            id,
            name,
            visible:false,
        });
    }
    setTreeData(id,name, data){
        if (this.props.type == '22') name = data.prop.fullName || name;
        this.setState({
            idCache: id,
            nameChache: name,
        });
    }
}
let conditionParamsBK={};
Main = Form.create({
    onFieldsChange(props, fields){
        for(let key in fields) {
            conditionParamsBK[fields[key].name] = fields[key].value
        }
    }
})(Main);
export default Main;
